/*!
 * 大文件代码分割器
 * 
 * 将超大的C文件按函数边界智能分割成多个片段
 */

use anyhow::{Result, Context};

/// 代码片段
#[derive(Debug, Clone)]
pub struct CodeChunk {
    pub content: String,
    pub start_line: usize,
    pub end_line: usize,
    pub functions: Vec<String>,
}

/// 代码分割器
pub struct CodeSplitter {
    max_lines_per_chunk: usize,
}

impl CodeSplitter {
    pub fn new(max_lines_per_chunk: usize) -> Self {
        Self { max_lines_per_chunk }
    }
    
    /// 将大文件分割成多个片段
    pub fn split_large_file(&self, content: &str, functions: &[String]) -> Result<Vec<CodeChunk>> {
        let lines: Vec<&str> = content.lines().collect();
        let total_lines = lines.len();
        
        // 如果文件不大，不需要分割
        if total_lines <= self.max_lines_per_chunk {
            return Ok(vec![CodeChunk {
                content: content.to_string(),
                start_line: 1,
                end_line: total_lines,
                functions: functions.to_vec(),
            }]);
        }
        
        log::info!("文件较大 ({} 行)，开始按函数边界分割...", total_lines);
        
        // 简单策略：按行数平均分割，尽量在函数边界处分割
        let mut chunks = Vec::new();
        let mut current_start = 0;
        
        while current_start < total_lines {
            let mut current_end = (current_start + self.max_lines_per_chunk).min(total_lines);
            
            // 尝试找到函数边界（找最近的空行或函数结束标志）
            if current_end < total_lines {
                for i in (current_start..current_end).rev() {
                    let line = lines[i].trim();
                    // 在函数结束的 } 处分割，或者空行
                    if line == "}" || line.is_empty() {
                        current_end = i + 1;
                        break;
                    }
                }
            }
            
            let chunk_content: String = lines[current_start..current_end].join("\n");
            
            // 提取这个片段中包含的函数名
            let chunk_functions = self.extract_functions_in_range(&chunk_content, functions);
            
            chunks.push(CodeChunk {
                content: chunk_content,
                start_line: current_start + 1,
                end_line: current_end,
                functions: chunk_functions,
            });
            
            log::info!("  片段 {}: 行 {}-{} ({} 行, {} 个函数)", 
                      chunks.len(), current_start + 1, current_end, 
                      current_end - current_start, chunks.last().unwrap().functions.len());
            
            current_start = current_end;
        }
        
        log::info!("分割完成：{} 个片段", chunks.len());
        Ok(chunks)
    }
    
    /// 提取片段中包含的函数名
    fn extract_functions_in_range(&self, content: &str, all_functions: &[String]) -> Vec<String> {
        all_functions.iter()
            .filter(|f| content.contains(&format!("{}(", f)))
            .cloned()
            .collect()
    }
}
